package logic

import (
	"context"
	"fmt"
	"math"
	"reflect"

	"googee/common/uniqueid"
	"googee/common/utils"
	"googee/service/account/model"
	"googee/service/account/rpc/internal/svc"
	"googee/service/account/rpc/types/account"

	"github.com/jinzhu/copier"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/sqlc"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

type AddAccountLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddAccountLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddAccountLogic {
	return &AddAccountLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

//  增加账户
func (l *AddAccountLogic) AddAccount(in *account.IdAddRequest) (*account.IdResponse, error) {
	resp := &account.IdResponse{}
	configValue := reflect.ValueOf(l.svcCtx.Config.Digital)
	precision := configValue.FieldByName(utils.FirstUpper(in.GetField())).Uint()

	err := l.svcCtx.SqlConn.TransactCtx(l.ctx, func(ctx context.Context, session sqlx.Session) error {
		err := l.svcCtx.AccountModel.AddField(l.ctx, in.Id, in.Field, in.Amount, uint8(precision))
		if err != nil {
			return err
		}

		transId := uniqueid.GenId()
		_, err = l.svcCtx.AccountLogModel.Insert(ctx, &model.AccountLog{
			Id:      uniqueid.GenId(),
			Dir:     TRANIN,
			Name:    in.Field,
			TransId: fmt.Sprintf("%v", transId),
			Amount:  in.Amount * int64(math.Pow10(int(precision))),
			UserId:  in.Id,
			Status:  1,
			Typ:     in.Typ,
			Subtyp:  in.Subtyp,
			Comment: in.Comment,
		})

		return err
	})

	// err := l.svcCtx.AccountModel.AddField(l.ctx, in.Id, in.Field, in.Amount, uint8(precision))
	if err == sqlc.ErrNotFound {
		return nil, status.Error(codes.NotFound, " 账户不存在 ")
	}

	accountmodel, err := l.svcCtx.AccountModel.FindOne(l.ctx, in.Id)
	if err == sqlc.ErrNotFound {
		return nil, status.Error(codes.NotFound, " 账户不存在 ")
	}

	copier.Copy(resp, accountmodel)
	return resp, nil
}
